<template>
    <div class="question-text">
        <template v-for="(part, index) in parsedParts" :key="index">
            <span v-if="!part.isInput">{{ part.text }}</span>
            <input
                v-else
                v-model="inputValues[part.inputIndex]"
                type="text"
                class="underline-input"
                :style="{
                    'pointer-events': readonly ? 'none' : 'auto',
                    width: calculateWidth(inputValues[part.inputIndex]),
                }"
                @input="onChange(part.inputIndex)"
            />
        </template>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";

interface Props {
    question?: string;
    answer?: string[];
    readonly?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
    question: "",
    answer: () => [],
    readonly: false,
});

const emit = defineEmits(["on-change"]);

// 计算解析后的部分
const parsedParts = computed(() => {
    let inputIndex = 0;
    return props.question.split(/(\[\])/).map((part) => {
        const isInput = part === "[]";
        return {
            text: part,
            isInput,
            inputIndex: isInput ? inputIndex++ : -1,
        };
    });
});

// 输入框值
const inputValues = ref<string[]>([]);

// 根据answer初始化inputValues
watch(
    () => props.question,
    () => {
        const inputCount = parsedParts.value.filter((p) => p.isInput).length;
        inputValues.value = props.answer.slice(0, inputCount);
        // 如果answer不够长，用空字符串填充
        while (inputValues.value.length < inputCount) {
            inputValues.value.push("");
        }
    },
    { immediate: true }
);

const calculateWidth = (value: string) => {
    const length = value ? value.length : 2;
    return `${Math.max(length, 15)}ch`;
};

const onChange = (index: number) => {
    emit("on-change", { index, value: inputValues.value });
};
</script>

<style scoped lang="less">
.underline-input {
    border: none;
    border-bottom: 1px solid #333;
    outline: none;
    text-align: center;
    margin: 0 2px;
    padding: 0 2px;
    min-width: 20px;
    background: transparent;
}

.underline-input:focus {
    border-bottom: 2px solid #409eff;
}
</style>
